<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>手写promise</title>
</head>

<body>
	<script type="text/javascript">
		function myPromise() {
			let self = this
			self.status = 'pengding' //状态
			self.value = null //成功的结果
			self.reason = null //失败的原因
			self.onFulfilledCallbacks = []//存储
			self.onRejectedCallbacks = []
			// 成功的回调
			function resolve(value) {
				// 状态处理
				if (self.status === 'pengding') {
					self.value = value //保存成功的结果
					self.status === 'fulfilled'
					self.onFulfilledCallbacks.forEach(item => item(value))//发布
				}
			}
			// 失败的回调
			function reject(reason) {
				if (self.status === 'pengding') {
					self.reason = reason //保存成功的结果
					elf.status === 'rejected'
					self.onRejectedCallbacks.forEach(item => item(reason))//发布
				}
			}
			// 立即执行一遍
			try {
				excutor(resolve, resject)
			} catch (err) {
				reject(err)
			}

		}
		// then方法
		myPromise.prototype.then = function (onFulfilled, onRejected) {
			// 状态改变,走.then
			onFulfilled = typeof onFulfilled === 'function' ?
				onFulfilled : function (data) { resolve(data) }

			onRejected = typeof onRejected === 'function' ?
				onRejected : function (err) { throw err }
			// 发布订阅模式  订阅
			if (this.status == 'pending') {
				this.onFulfilledCallbacks.push(onFulfilled)
				this.onRejectedCallbacks.push(onRejected)
			}
		}

		let demo = new myPromise((resolve, reject) => {
			console.log('完成')
			setTimeout(() => {
				resolve(123)
			}, 1000)
		})
		demo.then(data => console.log(data))
	</script>
</body>

</html>